import Vue from 'vue'
import vuex from 'vuex'
import axios from 'axios'

Vue.use(vuex)

const actions = {
	async getNews({commit}){
		try {
			const result = await axios.get('https://api.uixsj.cn/hitokoto/get?type=social')
			const newsObj = {id:Date.now(),title:result.data}
			commit('SAVE_NEWS',newsObj)
		} catch (error) {
			alert(error.message)
		}
	},
	addPerson({commit},personObj){
		commit('SAVE_PERSON',personObj)
	}
}

const mutations = {
	SAVE_NEWS(state,newsObj){
		state.newsList.unshift(newsObj)
	},
	SAVE_PERSON(state,personObj){
		state.persons.unshift(personObj)
	}
}

const state = {
	newsList:[
		{id:'76t87ig76',title:'震惊，两男子竟然做出这种事'},
		{id:'98audjwq2',title:'这十种水果，非常好！'},
		{id:'7yas7d2we',title:'北京昌平尚硅谷学员高薪就业'},
	],
	persons:[
		{id:'456789gfd',name:'小猪佩奇',sex:'女'},
		{id:'asdq3e32e',name:'小羊苏西',sex:'女'},
		{id:'76t76yi76',name:'帅气乔治',sex:'男'}
	]
}

const getters = {
	personCount(state){
		return state.persons.length
	}
}

const store = new vuex.Store({
	actions,
	mutations,
	state,
	getters
})

export default store